package cn.hnc.checkapi.redis;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;

@Service
public class CacheService {
   @Qualifier("redisTemplate")
   @Autowired
   RedisTemplate ObjectRedisTemplate;

   public Long getIncrementNum(String key) {
      RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, this.ObjectRedisTemplate.getConnectionFactory());
      Long counter = entityIdCounter.incrementAndGet();
      if (null == counter || counter == 1L) {
         int remainSeconds = getRemainSecondsOneDay(new Date());
         entityIdCounter.expire((long)remainSeconds, TimeUnit.SECONDS);
      }

      return counter;
   }

   public static Integer getRemainSecondsOneDay(Date currentDate) {
      LocalDateTime midnight = LocalDateTime.ofInstant(currentDate.toInstant(), ZoneId.systemDefault()).plusDays(1L).withHour(0).withMinute(0).withSecond(0).withNano(0);
      LocalDateTime currentDateTime = LocalDateTime.ofInstant(currentDate.toInstant(), ZoneId.systemDefault());
      long seconds = ChronoUnit.SECONDS.between(currentDateTime, midnight);
      return (int)seconds;
   }
}
